<script setup lang="ts">

import { ref, computed } from 'vue'
import type { Ref } from 'vue'
const loginusername: Ref<string> = ref('')

// const codeRef: Ref<any> = ref()
const time: Ref<number> = ref(60)//倒计时 先设置6s 一会改成60s
const codetext: Ref<string> = ref('发送验证码')
import { dosendmsgcodeFn, docheckcodeFn } from '@/api/register'
//防抖 
let timeout: any = null//记录倒计时 
let isSend = false//记录有没有正在发送验证码
// 发送验证码按钮点击事件
function sendcode() {
    /*
     方法1
    //当前已经有被点击，被点击了之后下次点击就不做处理了
    if (timeout != null) {//这个timeou不等于空 就是正在倒计时
        return
    }
    开启延迟 1s之内没有点击第二次 说明就是只点击了一次
    timeout = setTimeout(() => {

    }, 1000) 
    */

    /*  方法2
    if (isSend == true) {
        return
    }
    isSend = true
    */
    if (isSend == true) {
        return
    }
    isSend = true
   
    console.log('验证码发送了');

    const timer = setInterval(() => {
        isSend = false
        time.value--
        codetext.value = time.value + 's后重新获取'
        if (time.value == 0) {
            time.value = 60
            codetext.value = '重新获取'
            clearInterval(timer)
        }
    }, 1000)
    // dosendmsgcodeFn({ tel: code.value }).then(res => {//这个地方不传本地存储的值 会导致后续 注册成功一个账号然后拿这个账号去判断是否被注册 没办法检测到账号被注册过
    dosendmsgcodeFn({ tel: localStorage.getItem('tel') || '' }).then(res => {
        console.log(22222, res);
        code.value = res.data

    })
}
const code: Ref<string> = ref('')
const flag = computed(() => {
    return code.value.length == 5
})

import { useRoute, useRouter } from 'vue-router';
const router = useRouter()
import { showToast } from 'vant';
import { TRUE } from 'sass';
function nextstep3() {
    docheckcodeFn({ telcode: code.value, tel: localStorage.getItem('tel') || '', }).then(res => {
        console.log(23, res);
        // telcode.value=res.code
        if (res.data.code != '10007') {
            showToast(res.data.message)
            router.push('/register/step3')
        } else {
            showToast(res.data.message)
        }

    })

}
</script>

<template>

    <van-form>
        <van-cell-group inset style="height: 120px;">
            <van-field v-model="code" name="验证码" label="验证码" placeholder="请填写验证码"
                :rules="[{ required: true, message: '请填写验证码' }]">
                <template #button>
                    <!-- <van-button size="small" type="primary">发送验证码</van-button> -->
                    <van-button size="small" type="primary" @click="sendcode">
                        {{ codetext }}
                    </van-button>
                </template>
            </van-field>

        </van-cell-group>
        <div style="margin: 16px;">
            <van-button :disabled="!flag" rotepund block color="#f66" native-type="submit" @click="nextstep3">
                下一步
            </van-button>
        </div>

    </van-form>

</template>
